package com.sunny;

public class QuickSort {

    public static void main(String[] args) {

        QuickSort quickSort = new QuickSort();
        int[] arr = {2,1,8,5,3,9,0,2};
        quickSort.sort(arr, 0, arr.length-1);
        quickSort.print(arr, arr.length-1);

    }

    public void print(int[] arr, int n){
        for(int i=0;i<=n;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.println();
    }

    public void sort(int[] arr, int s, int t){

        if(s>=t){
            return;
        }

        int ind = quickSortCore(arr, s, t);
        sort(arr, s, ind-1);
        sort(arr, ind+1, t);

    }

    public int quickSortCore(int[] arr, int s, int t){
        int i = s;
        int j = t;
        int ind = i;
        int tmp = arr[ind];
        while (i<j){
//            System.out.println(i+" "+j);
            while (i<j && arr[j]>tmp){
                j--;
            }
            if(i==j)
                break;
            arr[ind] = arr[j];
            ind = j;
            i++;
            while (i<j && arr[i]<tmp){
                i++;
            }
            if(i==j)
                break;
            arr[ind] = arr[i];
            ind = i;
            j--;
        }
        arr[ind] = tmp;
        return ind;
    }

}
